import json

from django.http import JsonResponse
from django.views import View

from lapi_app.models.testcase_model.testcase import Variable_local
from lapi_app.view.user_view.token_check import access_token


class Var_edit(View):

    def post(self, request, *args, **kwargs):
        body = json.loads(request.body)
        if not access_token(body["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        name = body["local_variable_name"]
        result = body["local_variable_result"]
        description = body["local_variable_description"]
        user = body["user_id"]
        if name == '' or result == '':
            return JsonResponse({'code': 100, 'message': "参数不能为空"})
        else:
            if "var_id" not in body.keys():
                if Variable_local.objects.filter(local_name=name).exists():
                    return JsonResponse({'code': 101, 'message': "名称已存在，请重新输入"})
                else:
                    Variable_local.objects.create(local_name=name, local_result=result,
                                                  local_description=description, local_user_id=user)
                    return JsonResponse({'code': 200, 'message': "编辑全局变量成功"})
            else:
                Variable_local.objects.filter(id=body["var_id"]). \
                    update(local_name=name, local_result=result, local_description=description, local_user_id=user)
                return JsonResponse({'code': 200, 'message': "编辑全局变量成功"})
